import { _code, _signin, _auth, _login } from '../../common/api/signin'
import { NAME_REG, TEL_REG } from '../../utils/reg'
const computedBehavior = require('miniprogram-computed')
const app = getApp()
const countMax = 60
Component({
  behaviors: [computedBehavior],
  data: {
    uid: '',
    type: '',
    name: '',
    tel: '',
    code: '',
    rcode: '',
    countNum: countMax,
    countMax,
    agreed: false,
    submiting: false,
    resultShow: false,
    success: false,
    msg: ''
  },
  computed: {
    submitDisable() {
      return this.data.agreed && !this.data.submiting
    }
  },
  methods: {
    back() {
      let pages = getCurrentPages()
      if (pages.length > 1) {
        wx.navigateBack()
      } else {
        wx.redirectTo({
          url: '/pages/index/index'
        })
      }
    },
    checkChange(e) {
      if (e.detail.value.length > 0) {
        this.setData({
          agreed: true
        })
      } else {
        this.setData({
          agreed: false
        })
      }
    },
    inputHandler(e) {
      let attr = e.currentTarget.dataset.attr
      this.setData({
        [attr]: e.detail.value
      })
    },
    getCode() {
      if (!TEL_REG.test(this.data.tel)) {
        app.toast('请输入正确格式的手机号码')
        return
      }
      app.loading('加载中')
      _code(this.data.tel).then(res => {
        wx.hideLoading()
        wx.showModal({
          title: res.data.IsSuccess ? '温馨提示' : '对不起',
          content: res.data.Msg,
          showCancel: false
        })
        console.log(res.data.Data)
        this.data.rcode = res.data.IsSuccess ? res.data.Data : ''
        this.countDown()
      }).catch(err => {
        wx.hideLoading()
        console.log(err)
        wx.showModal({
          title: '对不起',
          content: '请求失败，请稍后再试',
          showCancel: false
        })
      })
    },
    countDown() {
      let timer = setInterval(() => {
        if (this.data.countNum < 1) {
          clearInterval(timer)
          this.data.countNum = countMax
          this.setData({
            countNum: this.data.countNum
          })
          return
        }
        this.data.countNum--
        this.setData({
          countNum: this.data.countNum
        })
      }, 1000)
    },
    showResult() {
      this.setData({
        resultShow: true
      })
    },
    hideResult() {
      this.setData({
        resultShow: false
      })
    },
    authRegist(e) {
      app.loading('加载中')
      let { iv, encryptedData } = e.detail
      let session_key = wx.getStorageSync('session_key')
      _auth(session_key, iv, encryptedData).then(res => {
        if (res.data.IsSuccess) {
          let uid = res.data.Data.unionId
          wx.setStorageSync('uid', uid)
          this.data.uid = uid
          this.doRegist()
        } else {
          // wx.hideLoading()
          // session_key过期 重新登录
          // wx.showModal({
          //   title: '对不起',
          //   content: res.data.Msg,
          //   showCancel: false
          // })
          console.log('session_key过期 重新登录')
          wx.login({
            success: r => {
              _login(r.code).then(res => {
                if (res.data.IsSuccess) {
                  wx.setStorageSync('session_key', res.data.Data.session_key)
                  let session_key = wx.getStorageSync('session_key')
                  wx.getUserInfo({
                    success: rr => {
                      let { iv, encryptedData } = rr
                      _auth(session_key, iv, encryptedData).then(res1 => {
                        if (res1.data.IsSuccess) {
                          let uid = res1.data.Data.unionId
                          wx.setStorageSync('uid', uid)
                          this.data.uid = uid
                          this.doRegist()
                        }
                      }).catch(err1 => {
                        wx.hideLoading()
                        console.log(err1)
                        wx.showModal({
                          title: '对不起',
                          content: '请求失败，请稍后再试',
                          showCancel: false
                        })
                      })
                    }
                  })
                } else {
                  wx.hideLoading()
                  wx.showModal({
                    title: '对不起',
                    content: res.data.Data,
                    showCancel: false
                  })
                }
              }).catch(err => {
                wx.hideLoading()
                console.log(err)
              })
            }
          })
        }
      }).catch(err => {
        wx.hideLoading()
        console.log(err)
        wx.showModal({
          title: '对不起',
          content: err,
          showCancel: false
        })
      })
      /**
       * 正常情况应该先检查session_key是否过期，
       * 但是后台程序如果没有维护session_key的有效期，
       * 就需要重新登录，获取新的session_key
       */
      // wx.checkSession({
      //   success: () => {
      //     console.log('登录未过期')
      //     let session_key = wx.getStorageSync('session_key')
      //     _auth(session_key, iv, encryptedData).then(res => {
      //       if (res.data.IsSuccess) {
      //         let uid = res.data.Data.unionId
      //         wx.setStorageSync('uid', uid)
      //         this.data.uid = uid             
      //         this.doRegist()
      //       }
      //     }).catch(err => {
      //       wx.hideLoading()
      //       console.log(err)
      //       wx.showModal({
      //         title: '对不起',
      //         content: err,
      //         showCancel: false
      //       })
      //     })
      //   },
      //   fail: () => {
      //     console.log('登录已过期，重新登录')
      //     wx.login({
      //       success: r => {
      //         _login(r.code).then(res => {
      //           if (res.data.IsSuccess) {
      //             wx.setStorageSync('session_key', res.data.Data.session_key)
      //             let session_key = wx.getStorageSync('session_key')
      //             _auth(session_key, iv, encryptedData).then(res => {
      //               if (res.data.IsSuccess) {
      //                 let uid = res.data.Data.unionId
      //                 wx.setStorageSync('uid', uid)
      //                 this.data.uid = uid
      //                 this.doRegist()
      //               }
      //             }).catch(err => {
      //               wx.hideLoading()
      //               console.log(err)
      //               wx.showModal({
      //                 title: '对不起',
      //                 content: '请求失败，请稍后再试',
      //                 showCancel: false
      //               })
      //             })
      //           } else {
      //             wx.hideLoading()
      //             wx.showModal({
      //               title: '对不起',
      //               content: res.data.Data,
      //               showCancel: false
      //             })
      //           }
      //         }).catch(err => {
      //           wx.hideLoading()
      //           console.log(err)
      //         })
      //       }
      //     })
      //   }
      // })
    },
    doRegist() {
      if (!NAME_REG.test(this.data.name)) {
        app.toast('请输入正确的中文姓名')
        return
      }
      if (!TEL_REG.test(this.data.tel)) {
        app.toast('请输入正确格式的手机号码')
        return
      }
      // if (this.data.code != this.data.rcode || !this.data.code || !this.data.rcode) {
      //   app.toast('请输入正确的短信验证码')
      //   return
      // }
      _signin(
        this.data.uid,
        this.data.name,
        this.data.tel,
        this.data.type
      ).then(res => {
        wx.hideLoading()
        console.log(res)
        this.setData({
          success: res.data.IsSuccess,
          msg: res.data.Msg
        })
        // wx.showModal({
        //   title: res.data.IsSuccess?'温馨提示':'对不起',
        //   content: res.data.Msg,
        //   showCancel: false,
        //   success: r => {
        //     if (res.data.IsSuccess) {
        //       wx.redirectTo({
        //         url: '/pages/index/index'
        //       })
        //     }
        //   }
        // })
        this.showResult()
      }).catch(err => {
        wx.hideLoading()
        console.log(err)
        wx.showModal({
          title: '对不起',
          content: err || '请求失败，请稍后再试',
          showCancel: false
        })
      })
    },
    onLoad(options) {
      let uid = wx.getStorageSync('uid')
      let type = options.type
      this.setData({
        uid,
        type
      })
    },
    onReady() { },
    onShow() { },
    onShareAppMessage() {
      return app.shareInfo
    }
  }
})